package com.hlg.xboot.core;

import org.springframework.util.StringUtils;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company: 中视数讯</p>
 * <p>Site: www.digi-zones.com</p>
 * <p>myblog: http://blog.csdn.net/xyang81</p>
 *
 * @author 杨信
 * @version 1.0
 * @date 2017/6/8
 */
public class DateEditor extends PropertyEditorSupport {

    private ArrayList<SimpleDateFormat> dateFormats = new ArrayList<>();

    public DateEditor() {
        dateFormats.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        dateFormats.add(new SimpleDateFormat("yyyy-MM-dd HH:mm"));
        dateFormats.add(new SimpleDateFormat("yyyy-MM-dd"));
        dateFormats.add(new SimpleDateFormat("HH:mm:ss"));
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (StringUtils.isEmpty(text)) {
            setValue(null);
        }
        else {
            for (SimpleDateFormat dateFormat : dateFormats) {
                try {
                    setValue(dateFormat.parse(text));
                    break;
                } catch (ParseException e) {
                    continue;
                }
            }
        }
    }

    @Override
    public String getAsText() {
        Date value = (Date) getValue();
        return (value != null ? this.dateFormats.get(0).format(value) : "");
    }
}
